package com.axy.imperfectblog.controller;

import com.axy.imperfectblog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/register")
    public String showRegisterPage(){
        return "register";
    }

    @PostMapping("/register")
    public String register(@RequestParam String username, @RequestParam String password, @RequestParam String email, Model model){
        try{
            userService.registerUser(username, password, email);
            return "redirect:/login";
        }catch(Exception e){
            model.addAttribute("error", "Registration failed:" + e.getMessage());
            return "register";
        }
    }

    @GetMapping("/login")
    public String showLoginPage(){
        return "login";
    }

    @PostMapping("/login")
    public String loginUser(@RequestParam String username, @RequestParam String password, Model model){
        if(userService.loginUser(username, password) != null){
            return "redirect:/blog";
        }else{
            model.addAttribute("error","Invalid username or password");
            return "login";
        }
    }
}
